// user 模块
const { login } = require('../controller/user')
const { SuccessModel, ErrorModel } = require('../model/resBaseModel')
const { get, set} = require('../db/redis')

// 设置cookie的过期时间
// 设置一天后过期
const getCookieExpires = () => {
  const d = new Date()
  d.setTime(d.getTime() + (24 * 60 * 60 * 1000))
  return d.toGMTString()
}

const handleUserRouter = (req, res) => {
  const method = req.method
  const url = req.url

  if (method === 'POST' && req.path === '/api/user/login') {
    const { username, password } = req.body
    const result = login(username, password);
    return result.then(data => {
      if (data.username) {

        // 种cookie, path=/ 表示在根目录下都可以访问
        //res.setHeader('Set-Cookie', `username=${data.username}; path=/; httpOnly; expires=${getCookieExpires()}`)

        // session 保存登录信息
        req.session.username = data.username
        req.session.realname = data.realname
        set(req.sessionId, req.session)

        console.log('req.session: ', req.session);

        return new SuccessModel("登录成功")
      }
      return new ErrorModel('登录失败')
    })
  }

  // 登录验证测试

  if (method === 'GET' && req.path === '/api/user/login-test') {
    if (req.session.username) {
      return Promise.resolve(
        new SuccessModel({
          username: req.session.username,
          realname: req.session.realname
        })
      )
    }
    return Promise.resolve(
      new ErrorModel('尚未登录')
    )
  }
}

module.exports = handleUserRouter